<template>
  <el-upload
      class="img-upload"
      ref="upload"
      action=""
      :http-request="upload"
      with-credentials
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="handleSuccess"
      multiple
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
  </el-upload>
</template>

<script>

import {Message, MessageBox} from "element-ui";
export default {
  name: "ImgUpload",
  data() {
    return {
      fileList: [],
      url: ""
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    async upload(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      const res = await this.$http.post('/api/covers', formData)
          .then(res => {
            console.log(res)
            //if (res && res.status === 200) {
              this.url = res
              console.log('上传图片成功')
            //}
          })
          .catch(error => {
            console.log('图片上传失败')
          });
    },
    handlePreview(file) {
      console.log(file);
      // 此处的 file 是整个文件
      // console.log(file.response)
    },
    handleExceed(files, fileList) {
      Message.warning(`当前限制选择 1 个文件，本次选择了 ${
          files.length
      } 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      /*this.$message({
        message: `当前限制选择 1 个文件，本次选择了 ${
            files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`,
        type: "warning"
      });*/
    },
    beforeRemove(file, fileList) {
      return MessageBox.confirm(`确定移除 ${file.name}？`,{});
    },
    handleSuccess(response) {
      //this.url = response;
      console.log(this.url)
      this.$emit("onUpload",this.url);
      Message.success("上传成功");
      /*this.$message({
        message: "上传成功",
        type: "success"
      });*/

    },
    clear() {
      this.$refs.upload.clearFiles();
    }
  }
}
;
</script>

<style scoped>
.img-upload {
  /*height: 200px;*/
}
</style>